//
//  EFengContactController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/2/16.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "EFengContactController.h"
#import "WZFlowLayout.h"
#import "EFengOrganizationCell.h"
#import "CDepartmentMgr.h"
#import "CContactMgr.h"
#import "CDepartmentModel.h"
#import "CPresenceMgr.h"
#import "CPresenceModel.h"
#import "CContactModel.h"
#import "EFengOrganizationDepCell.h"
#import "GroupListVC.h"
#import "EFengDiscussController.h"
#import "EFengOrganizationHeaderView.h"
#import "EFengMIneContactController.h"
#import "GroupMemberDetailVC.h"
#import "MyInformationVC.h"
#import "CFolderMgr.h"
#import "EFengDepListButton.h"
#import "CXmppMgr.h"
#import "CGroupMgr.h"
#import "CGroupModel.h"
#import "NSArray+PinYin.h"
#import "EFengDisCussCreateController.h"
#import "WZNavigationController.h"
#import "CRecentlyContactMgr.h"
#import "CRecentlyContactModel.h"
#import "CXmppRequestMgr.h"
#import "SettingNormalCell.h"
#import "GroupMenberCell.h"
#import "UIImageView+WebCache.h"
#import "CHChatRoomBase.h"
#import "EFengOrganizationListView.h"
#import "UIBarButtonItem+category.h"
#import "EFengContactButton.h"
#import "WZSearchController.h"
#import "EFengOrganizationBaseView.h"
#import "MBProgressHUD+WZ.h"
#import "WZScrollView.h"
#import "CMessageMgr.h"
#import "EFengChatListView.h"
#import "CUserSettingModel.h"
#import "CUserSettingMgr.h"
#import "MoreSettingVC.h"
#import "CMessageDraftMgr.h"
#define buttonCount 4


@interface EFengContactController ()<UICollectionViewDataSource, UICollectionViewDelegate, EFengOrganizationListViewDelegate, UISearchBarDelegate, EFengOrganizationBaseViewDelegate, UIScrollViewDelegate,EFengChatListViewDelegate>


StrongProperty UICollectionView *collectionView;
StrongProperty WZFlowLayout *flowLayout;
StrongProperty EFengOrganizationListView *leftView;
StrongProperty NSArray *depList;
StrongProperty NSArray *contactList;
StrongProperty CDepartmentMgr *depMgr;
StrongProperty CContactMgr *conMgr;
StrongProperty CPresenceMgr *preMgr;
StrongProperty CGroupMgr *groupMgr;
StrongProperty CContactModel *curContact;
StrongProperty CDepartmentModel *curDepModel;
WeakProperty UIScrollView *depScrollView;
StrongProperty NSMutableArray *fatherDepArray;
StrongProperty NSMutableArray *depScrollButtonArray;
WeakProperty UIView *organizationView;
StrongProperty  UISearchBar *searchBar;
StrongProperty  WZSearchController *searchController;
StrongProperty  WZScrollView *scrollView;
StrongProperty EFengOrganizationBaseView *groupView;
StrongProperty EFengOrganizationBaseView *discussView;
StrongProperty EFengOrganizationBaseView *mineContactView;
StrongProperty EFengChatListView *moreView;
AssignProperty BOOL isShowMoreView;
WeakProperty UIView *rightView;
@property (nonatomic,assign) selectType type;
@property (nonatomic) BOOL isNeedrefresh;
@property (nonatomic,strong)NSArray *colorArray;
@end

@implementation EFengContactController

- (void)dealloc
{
    //组织架构相关
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPUPDATEORGNAZATION object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPDIDRECEIVEPRESENCE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPDIDGETDEPTREE object:nil];
    //群相关
    [[NSNotificationCenter defaultCenter] removeObserver:self name:k_XMPPUPDATEGROUPLIST object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:k_XMPPGETGROUPLIST object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPUPDATEGROUPINFO object:nil];
    //讨论组相关
    [[NSNotificationCenter defaultCenter] removeObserver:self name:k_XMPPGETDISCUSSIONLIST object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPCREATEDISCUSSION object:nil];
    //我的联系人相关
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPDIDGERECENTLYLIST object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPDIDGETKEFULIST object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPDIDGETWAIBULIST object:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    
    if (IsIOS7) {
        [self.navigationController.navigationBar setBarTintColor:RGBCOLOR(44, 170, 253)];
    } else {
        [self.navigationController.navigationBar setTintColor:RGBCOLOR(44, 170, 253)];
    }
    
}
-(NSArray *)colorArray
{
    if (_colorArray == nil) {
        UIColor *color1 = RGBCOLORWITH16COLOR(0x7ba4ed);
        UIColor *color2 = RGBCOLORWITH16COLOR(0xf6bf3c);
        UIColor *color3 = RGBCOLORWITH16COLOR(0x55d4ef);
        UIColor *color4 = RGBCOLORWITH16COLOR(0xa9ca56);
        UIColor *color5 = RGBCOLORWITH16COLOR(0x3bbbff);
        UIColor *color6 = RGBCOLORWITH16COLOR(0xefd154);
        UIColor *color7 = RGBCOLORWITH16COLOR(0xfb8c52);
        UIColor *color8 = RGBCOLORWITH16COLOR(0x58bfbf);
        _colorArray = @[color1,color2,color3,color4,color5,color6,color7,color8];
    }
    return _colorArray;
}
- (EFengChatListView *)moreView
{
    if (_moreView == nil) {
        _moreView = [[EFengChatListView alloc] initWithFrame:CGRectZero];
        _moreView.chatListDelegate = self;
        [self.view addSubview:_moreView];
    }
    return _moreView;
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (_searchController.active) {
        [_searchController setActive:NO];
    }
    self.isShowMoreView = NO;
    [self.moreView hieChatListView];
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}

- (EFengOrganizationBaseView *)discussView
{
    if (_discussView == nil) {
        _discussView =[[EFengOrganizationBaseView alloc] init];
        _discussView.EFengOrganizationBaseViewDelegate = self;
//        _discussView.tableView.bounces = NO;
    }
    return _discussView;
}
-(BOOL)mineContactViewShowNoitceView
{
    NSArray *array = [_conMgr loadWaiBuList];
    NSArray *array1 = [_conMgr loadKeFuList];
    NSMutableArray *changyong = [NSMutableArray array];
    NSArray *array2 = [[[CRecentlyContactMgr alloc] init] loadAllRecentlyContacts];
    if (array2.count>0) {
        for (CRecentlyContactModel *model in array2) {
            CContactModel *contact = [_conMgr loadNotDelContactWithUserId:model.userId];
            if (contact) {
                contact.yuLiuZiduan3 = @"";
                [changyong addObject:contact];
            }
        }
        //bug 8838 fixed by lixu
    }
    self.mineContactView.noListLabel.text = @"您暂时没有添加联系人";
    self.mineContactView.createButton.hidden = YES;
    if (array.count + array1.count + changyong.count > 0) {
        return YES;
    }
    else
    {
        return NO;
    }
}
- (EFengOrganizationBaseView *)groupView
{
    if (_groupView == nil) {
        _groupView = [[EFengOrganizationBaseView alloc] init];
        _groupView.EFengOrganizationBaseViewDelegate = self;
//        _groupView.tableView.bounces = NO;
    }
    return _groupView;
}

- (EFengOrganizationBaseView *)mineContactView
{
    if (_mineContactView == nil) {
        _mineContactView = [[EFengOrganizationBaseView alloc] init];
        _mineContactView.EFengOrganizationBaseViewDelegate = self;
//        _mineContactView.tableView.bounces = NO;
    }
    return _mineContactView;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if (IsIOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationItem setNewTitleCenter:@"联系人"];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"btn-search" title:nil target:self sel:@selector(search) titleFont:Font18 titleColor:WhiteColor];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"btn-more" title:nil target:self sel:@selector(showMoreView) titleFont:Font18 titleColor:WhiteColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUsePresence) name:K_XMPPDIDRECEIVEPRESENCE object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUseUpdateOrgation) name:K_XMPPUPDATEORGNAZATION object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUseGetOrgation) name:K_XMPPDIDGETDEPTREE object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateGroupList) name:k_XMPPUPDATEGROUPLIST object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateGroupList) name:k_XMPPGETGROUPLIST object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateGroupList) name:K_XMPPUPDATEGROUPINFO object:nil];
    //讨论组相关
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDiscussList) name:k_XMPPGETDISCUSSIONLIST object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDiscussList) name:K_XMPPCREATEDISCUSSION object:nil];

    //我的联系人相关
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addKeFuContact) name:K_XMPPDIDGETKEFULIST object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addOftenContact) name:K_XMPPDIDGERECENTLYLIST object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addWaiBuContact) name:K_XMPPDIDGETWAIBULIST object:nil];
    self.leftView.frame = CGRectMake(0, 0, 100.0f * (HARDWARE_SCREEN_WIDTH / 320.0f), HARDWARE_SCREEN_HEIGHT - 44.0f - StatusBarHeight - 49.0f);
    [self.view addSubview:self.leftView];
    
    UIView *right = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.leftView.frame),0, HARDWARE_SCREEN_WIDTH - self.leftView.width, self.leftView.height)];
    [self.view addSubview:right];
    self.rightView = right;
    
    UIScrollView *depLabel = [[UIScrollView alloc] init];
    depLabel.hidden = NO;
    depLabel.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH - self.leftView.width, 35.0f);
    depLabel.backgroundColor = RGBCOLORWITH16COLOR(0xe3eef6);
    [self.rightView addSubview:depLabel];
    self.depScrollView = depLabel;

    self.collectionView.frame = CGRectMake(0, CGRectGetMaxY(self.depScrollView.frame), HARDWARE_SCREEN_WIDTH - self.leftView.width, self.rightView.height - self.depScrollView.height);
    [self.rightView addSubview:self.collectionView];
    
    
    self.groupView.frame = CGRectMake(CGRectGetMaxX(self.leftView.frame), 0, HARDWARE_SCREEN_WIDTH - self.leftView.width, self.leftView.height);
    [self.view addSubview:self.groupView];
   
    
    self.discussView.frame = CGRectMake(CGRectGetMaxX(self.leftView.frame), 0, HARDWARE_SCREEN_WIDTH - self.leftView.width, self.leftView.height);
    [self.view addSubview:self.discussView];
    

    self.mineContactView.frame = CGRectMake(CGRectGetMaxX(self.leftView.frame), 0, HARDWARE_SCREEN_WIDTH - self.leftView.width, self.leftView.height);
    [self.view addSubview:self.mineContactView];
    self.depMgr = [[CDepartmentMgr alloc] init];
    self.conMgr = [[CContactMgr alloc] init];
    self.preMgr = [[CPresenceMgr alloc] init];
    self.groupMgr = [[CGroupMgr alloc] init];
    
//    self.curContact = [self.conMgr loadCurContact];
    
    [self handleUseGetOrgation];
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //搜索相关
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    _searchBar.backgroundImage = [UIImage imageNamed:@"BG-search"];
    //test 联系人搜索
    _searchBar.placeholder = @"搜索";
    _searchBar.delegate = self;
    _searchBar.hidden = YES;
    // 添加 searchbar 到 headerview
    [self.view addSubview:_searchBar];
    _searchController = [[WZSearchController alloc] initWithSearchBar:_searchBar contentsController:self];
}

- (void)search
{
//    [self.searchDisplayController setActive:YES animated:NO];
    [self.searchBar becomeFirstResponder];
    __weak EFengContactController *weakSelf = self;
    
    
    [weakSelf.searchController setCellForRowAtIndexPathCompletion:^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
        
        NSArray *searchArray = weakSelf.searchController.searchSectionListArray[indexPath.section];
        id lastContact = searchArray[indexPath.row];
        if ([lastContact isKindOfClass:[CGroupModel class]]) {
            CGroupModel *groupModel = (CGroupModel *)lastContact;
            
            static NSString *NormalCellIdentifier = @"SettingNormalCell";
            SettingNormalCell *normalCell = [tableView dequeueReusableCellWithIdentifier:NormalCellIdentifier];
            if (normalCell == nil) {
                normalCell = [[[NSBundle mainBundle] loadNibNamed:@"SettingNormalCell" owner:self options:nil] objectAtIndex:0];
            }
            if (groupModel.groupType == 1) {
                [normalCell.icon setImage:[UIImage imageNamed:@"icon-discussList"] forState:UIControlStateNormal];
            } else {
                [normalCell.icon setImage:[UIImage imageNamed:@"icon-Group"] forState:UIControlStateNormal];
            }
            
            normalCell.icon.layer.cornerRadius = 5.0f/2;
            normalCell.icon.layer.masksToBounds = YES;
            [normalCell.titleLabel setText:[NSString stringWithFormat:@"%@(%zd)",groupModel.GroupName,groupModel.UserNum]];
            normalCell.rightArrow.hidden = YES;
            NSInteger rows = [tableView numberOfRowsInSection:indexPath.section];
            
            if(indexPath.row == rows - 1){
                
                [normalCell.seperatorLine setHidden:YES];
            }
            else{
                [normalCell.seperatorLine setHidden:NO];
            }
            return normalCell;
            
        } else {
            CContactModel *contact = (CContactModel *)lastContact;
            static NSString *GroupCellIdentifier = @"GroupMenberCell";
            GroupMenberCell *groupMemberCell = [tableView dequeueReusableCellWithIdentifier:GroupCellIdentifier];
            if (groupMemberCell == nil) {
                groupMemberCell = [[[NSBundle mainBundle] loadNibNamed:@"GroupMenberCell" owner:self options:nil] objectAtIndex:0];
            }
            groupMemberCell.Arrow.hidden = YES;
            if ([contact.yuLiuZiduan3 isEqualToString:@"isKefu"] && contact.isDel == 0) {
                [groupMemberCell.icon setImage:[UIImage imageNamed:@"head-kefu"]];
            } else {
                [groupMemberCell.icon sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:contact.UserID]] placeholderImage:[UIImage imageNamed:@"80-80"]];
            }

            //        [groupMemberCell.titleLabel setText:@"测试名字"];
            [groupMemberCell.titleLabel setText:contact.UserName];
            NSInteger rows = [tableView numberOfRowsInSection:indexPath.section];
            
            if(indexPath.row == rows - 1)
            {
                [groupMemberCell.seperatorLine setHidden:YES];
            } else {
                groupMemberCell.seperatorLine.hidden = NO;
            }
            return groupMemberCell;
            
        }
        
    }];
    
    [weakSelf.searchController setHeightForRowAtIndexPathCompletion:^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
        return 60.0f;
    }];
    
    [weakSelf.searchController setDidSelectRowAtIndexPathCompletion:^(UITableView *tableView, NSIndexPath *indexPath) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        [weakSelf.searchController.searchBar endEditing:YES];
        NSArray *rowArray = weakSelf.searchController.searchSectionListArray[indexPath.section];
        UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        id model = rowArray[indexPath.row];
        if ([model isKindOfClass:[CContactModel class]]) {
            CContactModel *contact = (CContactModel *)model;
            //bug 9345 fixed by lixu
            if ([contact.UserID isEqualToString:self.curContact.UserID]) {
                MyInformationVC *myInfo = [[MyInformationVC alloc] init];
                //            myInfo.curuser = model;
                nav.navigationBarHidden = NO;
                self.navigationController.navigationBarHidden = YES;
                
                [nav pushViewController:myInfo animated:YES];
            }
            else
            {
            CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
            chat.group = nil;
            chat.member = contact;
            
            nav.navigationBarHidden = NO;
            self.navigationController.navigationBarHidden = YES;
            
            [nav pushViewController:chat animated:YES];
            }

        } else if ([model isKindOfClass:[CGroupModel class]]) {
            CGroupModel *groupModel = (CGroupModel *)model;
            if (groupModel) {
                CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
                chat.group = groupModel;
                chat.member = nil;
                UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                nav.navigationBarHidden = NO;
                self.navigationController.navigationBarHidden = YES;
                
                [nav pushViewController:chat animated:YES];
            } else {
                
            }
            
            
        }

    }];
}

#pragma mark 群组相关

- (void)listBtnClick
{

    //bug 9483 fixed by lixu
    switch (self.type) {
        case organization:
        {
            [self loadContact];
            
        }
            break;
        case group:
        {
            self.groupView.type = group;
            [self updateGroupList];
            
        }
            break;
        case discuss:
        {
            self.discussView.type = discuss;
            [self updateDiscussList];

        }
            break;
        case mineContact:
        {
            self.mineContactView.type = mineContact;
            [self addKeFuContact];
            [self addOftenContact];
            [self addWaiBuContact];
        }
            break;

        default:
            break;
    }
}

- (void)addWaiBuContact
{
    NSArray *array = [_conMgr loadWaiBuList];
        self.mineContactView.waibuList = [array copy];
//        self.mineContactView.nolistView.hidden = YES;
     self.mineContactView.nolistView.hidden = [self mineContactViewShowNoitceView];
}


- (EFengOrganizationListView *)leftView
{
    if (_leftView == nil) {
        _leftView = [[EFengOrganizationListView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _leftView.showsVerticalScrollIndicator = NO;
        _leftView.backgroundColor = [UIColor clearColor];
        _leftView.organizationListViewDelegate = self;
    }
    return _leftView;
}

- (WZFlowLayout *)flowLayout
{
    if (_flowLayout == nil) {
        _flowLayout = [[WZFlowLayout alloc] init];
        _flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _flowLayout.itemSize = CGSizeMake((HARDWARE_SCREEN_WIDTH - self.leftView.width) / 3.0f, (HARDWARE_SCREEN_WIDTH - self.leftView.width) / 3.0f);
        _flowLayout.minimumInteritemSpacing = 0.0f;
        _flowLayout.headerReferenceSize = CGSizeMake(HARDWARE_SCREEN_WIDTH - self.leftView.width, 0.5f);
        _flowLayout.minimumLineSpacing = 0.0f;
    }
    return _flowLayout;
}

- (UICollectionView *)collectionView
{
    if (_collectionView == nil) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.backgroundColor = WhiteColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[EFengOrganizationCell class] forCellWithReuseIdentifier:@"organizationCell"];
        [_collectionView registerClass:[EFengOrganizationHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"collectionViewheader"];
        
    }
    return _collectionView;
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    NSInteger section = 0;
    if (self.depList.count > 0) {
        section ++;
    }
    if (self.contactList.count > 0) {
        section ++;
    }
    return section;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSInteger rows = 0;
    switch (section) {
        case 0:
        {
            if (self.depList.count > 0) {
                rows = self.depList.count;
            } else {
                rows = self.contactList.count;
            }
        }
            break;
        case 1:
        {
            rows = self.contactList.count;
    
        }
            break;
 
        default:
            break;
    }
    return rows;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    static NSString *collectionViewheader = @"collectionViewheader";
    EFengOrganizationHeaderView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:collectionViewheader forIndexPath:indexPath];
    if (indexPath.section == 0) {
        view.backgroundColor = ClearColor;
    } else {
        view.backgroundColor = RGBCOLOR(212, 212, 212);
    }
//    if (indexPath.section == 0 && self.depList.count > 0) {
//        view.titleLabel.text = @"部门";
//    } else {
//        view.titleLabel.text = @"人员";
//    }
    return view;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    EFengOrganizationCell *cell = [EFengOrganizationCell organizationCellWithCollectionview:collectionView indexPath:indexPath];
    cell.color = self.colorArray[indexPath.row%8];
    if (indexPath.section == 0 && self.depList.count > 0) {
        CDepartmentModel *dep = self.depList[indexPath.row];
        cell.organization = dep;
    } else {
        CContactModel *con = self.contactList[indexPath.row];
        cell.organization = con;
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.isNeedrefresh = YES;
    if (indexPath.section == 0 && self.depList.count > 0) {
        CDepartmentModel *dep = self.depList[indexPath.row];
        self.curDepModel = dep;
        self.depList = [self.depMgr loadDepartments:dep.DEPTID];
        self.contactList = [self.conMgr loadContactByDeptID:dep.DEPTID];
        [self.contactList enumerateObjectsUsingBlock:^(CContactModel  *obj, NSUInteger idx, BOOL *stop) {
            CPresenceModel *presence = [self.preMgr getPresenceWithUserCode:obj.UserCode];
            if ([presence.IsAvailable isEqualToString:@"在线"] || [presence.pcAvailable isEqualToString:@"在线"]) {
                obj.IsAvailable = @"在线";
            } else {
                obj.IsAvailable = @"离线";
            }
        }];
        
        [self.fatherDepArray removeAllObjects];
        [self loadAllFatherDepInfoWithDepModel:dep];
        [self.fatherDepArray addObject:dep];
        [self.fatherDepArray removeObjectAtIndex:0];
        [self.fatherDepArray removeObjectAtIndex:0];
        
        [self setupDepScrollView];
        [self.collectionView reloadData];

        
    } else {
        CContactModel *member = [self.contactList objectAtIndex:indexPath.item];
        UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        nav.navigationBarHidden = NO;
        self.navigationController.navigationBarHidden = YES;
        
        if ([member.UserID isEqualToString:self.curContact.UserID]) {
            MyInformationVC *mine = [[MyInformationVC alloc] init];
            [nav pushViewController:mine animated:YES];
        } else {
            CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
            chat.group = nil;
            chat.member = member;
            [nav pushViewController:chat animated:YES];

        }
        
        
    }
}

#pragma mark 加载所有父部门信息
- (NSMutableArray *)fatherDepArray
{
    if (_fatherDepArray == nil) {
        _fatherDepArray = [NSMutableArray array];
    }
    return _fatherDepArray;
}


- (void)loadAllFatherDepInfoWithDepModel:(CDepartmentModel *)depModel
{
    if (M_ISSTRNULL(depModel.DeptFatherID) || [depModel.DeptFatherID isEqualToString:@"0"]) {
        return;
    }
    CDepartmentModel *model = [self.depMgr loadDepartment:depModel.DeptFatherID];
    if (self.fatherDepArray.count > 0) {
        [self.fatherDepArray insertObject:model atIndex:0];
    } else {
        [self.fatherDepArray addObject:model];
    }
    
    [self loadAllFatherDepInfoWithDepModel:model];
}

#pragma mark 设置depScrollView

- (NSMutableArray *)depScrollButtonArray
{
    if (_depScrollButtonArray == nil) {
        _depScrollButtonArray = [NSMutableArray array];
    }
    return _depScrollButtonArray;
}

- (void)setupDepScrollView
{
    if (self.fatherDepArray.count > 0) {
        self.depScrollView.hidden = NO;
        self.collectionView.frame = CGRectMake(0, CGRectGetMaxY(self.depScrollView.frame), HARDWARE_SCREEN_WIDTH - self.leftView.width, self.rightView.height - self.depScrollView.height);
        [self.depScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self.depScrollButtonArray removeAllObjects];
        
        for (int i = 0; i < self.fatherDepArray.count; i ++) {
            CDepartmentModel *dep = self.fatherDepArray[i];
            
            if (i == self.fatherDepArray.count - 1) {
                EFengDepListButton *btn = [EFengDepListButton buttonWithType:UIButtonTypeCustom];
                btn.depModel = dep;
                [self.depScrollView addSubview:btn];
                [self.depScrollButtonArray addObject:btn];
 
            } else {
                EFengDepListButton *btn = [EFengDepListButton buttonWithType:UIButtonTypeCustom];
                btn.depModel = dep;
                [btn addTarget:self action:@selector(depscrollButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
                [self.depScrollView addSubview:btn];
                [self.depScrollButtonArray addObject:btn];
                
                EFengDepListButton *arrowbtn = [EFengDepListButton buttonWithType:UIButtonTypeCustom];
                [arrowbtn setImage:[UIImage imageNamed:@"mapModelBack"] forState:UIControlStateNormal];
                arrowbtn.width = arrowbtn.currentImage.size.width;
                arrowbtn.userInteractionEnabled = NO;
                [self.depScrollView addSubview:arrowbtn];
                [self.depScrollButtonArray addObject:arrowbtn];

                
            }
            
        }
        
    [self.depScrollButtonArray enumerateObjectsUsingBlock:^(EFengDepListButton *obj, NSUInteger idx, BOOL *stop) {
        if (idx == 0) {
            obj.x = 10.0f;
        } else {
            EFengDepListButton *preBtn = self.depScrollButtonArray[idx - 1];
            obj.x = CGRectGetMaxX(preBtn.frame);
        }
        obj.y = 0;
        obj.height = self.depScrollView.height;
    }];
        EFengDepListButton *last = self.depScrollButtonArray.lastObject;
        self.depScrollView.contentSize = CGSizeMake(CGRectGetMaxX(last.frame), 0);
    } else {
        self.depScrollView.hidden = YES;
        self.collectionView.frame = CGRectMake(0, 10, HARDWARE_SCREEN_WIDTH - self.leftView.width, self.rightView.height);
    }
}

- (void)depscrollButtonDidClick:(EFengDepListButton *)button
{
    
    self.depList = [self.depMgr loadDepartments:button.depModel.DEPTID];
    self.contactList = [self.conMgr loadContactByDeptID:button.depModel.DEPTID];
    [self.contactList enumerateObjectsUsingBlock:^(CContactModel  *obj, NSUInteger idx, BOOL *stop) {
        CPresenceModel *presence = [self.preMgr getPresenceWithUserCode:obj.UserCode];
        if ([presence.IsAvailable isEqualToString:@"在线"] || [presence.pcAvailable isEqualToString:@"在线"]) {
            obj.IsAvailable = @"在线";
        } else {
            obj.IsAvailable = @"离线";
        }
    }];

    
    [self.fatherDepArray removeAllObjects];
    [self loadAllFatherDepInfoWithDepModel:button.depModel];
    [self.fatherDepArray addObject:button.depModel];
    [self.fatherDepArray removeObjectAtIndex:0];
    [self.fatherDepArray removeObjectAtIndex:0];
    
    [self setupDepScrollView];
    [self.collectionView reloadData];

}

#pragma mark 群组相关

- (void)updateGroupList
{
    
        NSMutableArray *mine = [NSMutableArray array];
        NSMutableArray *other = [NSMutableArray array];
        
        NSArray *array = [self.groupMgr loadAllGroup];
        if (array.count > 0) {
            for (CGroupModel *group in array) {
                if ([group.OwnerId isEqualToString:self.curContact.UserID]) {
                    [mine addObject:group];
                } else {
                    [other addObject:group];
                }
            }
            self.groupView.nolistView.hidden = YES;
        } else {
            self.groupView.nolistView.hidden = NO;
            self.groupView.createButton.hidden = YES;
            self.groupView.noListLabel.text = @"您还没有加入过群";
        }
        //bug 9487 fixed by lixu
        self.groupView.mineGroupArray = [mine copy];
        self.groupView.otherGroupArray = [other copy];
}

#pragma mark 讨论组相关



- (void)updateDiscussList
{
   
        NSMutableArray *discussArrayM = [NSMutableArray array];
    NSArray *discussArray = [self.groupMgr loadAllDiscussList];
    
        for (CGroupModel *discuss in discussArray) {
            if ([discuss.OwnerId isEqualToString:self.curContact.UserID]) {
                [discussArrayM addObject:discuss];
            } else {
                if (discuss.isShow) {
                    [discussArrayM addObject:discuss];
                }
            }
        }
        if (discussArrayM.count > 0) {
            self.discussView.nolistView.hidden = YES;
        } else {
            self.discussView.nolistView.hidden = NO;
            self.discussView.createButton.hidden = NO;
            self.discussView.noListLabel.text = @"您还没有加入过讨论组";
        }
        self.discussView.discussionArray = [discussArrayM copy];
}


- (void)createNewDiscuss
{
    [[[CDepartmentMgr alloc] init] updateAllDeptNotSelected:nil];
    [[[CContactMgr alloc] init] updateAllContactNotSelected:nil];
    EFengDisCussCreateController *cre = [[EFengDisCussCreateController alloc] init];
    cre.group = nil;
    WZNavigationController *nav = [[WZNavigationController alloc] initWithRootViewController:cre];
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark 我的联系人相关

- (void)addKeFuContact
{
    if (self.type == mineContact) {
        NSArray *array = [_conMgr loadKeFuList];
        if (array.count>0) {
            self.mineContactView.kefuList = array;
//            self.mineContactView.nolistView.hidden = YES;
            self.mineContactView.nolistView.hidden = [self mineContactViewShowNoitceView];
        }
        
    }

}


- (void)addOftenContact
{
    if (self.type == mineContact) {
        
        NSMutableArray *changyong = [NSMutableArray array];
        NSArray *array = [[[CRecentlyContactMgr alloc] init] loadAllRecentlyContacts];
        if (array.count>0) {
            for (CRecentlyContactModel *model in array) {
                CContactModel *contact = [_conMgr loadNotDelContactWithUserId:model.userId];
                if (contact) {
                    contact.yuLiuZiduan3 = @"";
                    [changyong addObject:contact];
                }
            }
            //bug 8838 fixed by lixu
        }
        self.mineContactView.changyongList = [NSArray sortArray:changyong];
//        self.mineContactView.nolistView.hidden = YES;
         self.mineContactView.nolistView.hidden = [self mineContactViewShowNoitceView];

     
    }

}


#pragma mark 组织架构相关
- (void)handleUsePresence
{
    [self listBtnClick];
    
}
-(void)loadContact
{
    if (self.curDepModel == nil) {
        return;
    }
    self.depList = [self.depMgr loadDepartments:self.curDepModel.DEPTID];
    self.contactList = [self.conMgr loadContactByDeptID:self.curDepModel.DEPTID];
    [self.contactList enumerateObjectsUsingBlock:^(CContactModel  *obj, NSUInteger idx, BOOL *stop) {
        CPresenceModel *presence = [self.preMgr getPresenceWithUserCode:obj.UserCode];
        if ([presence.IsAvailable isEqualToString:@"在线"] || [presence.pcAvailable isEqualToString:@"在线"]) {
            obj.IsAvailable = @"在线";
        } else {
            obj.IsAvailable = @"离线";
        }
    }];
    [self.collectionView reloadData];
}
- (void)handleUseUpdateOrgation
{
    self.curContact = [self.conMgr loadCurContact];
    NSArray *deps = [self.depMgr loadDepartments:@"0"];
    CDepartmentModel *dep = deps.lastObject;
    NSArray *contactArray = [self.conMgr loadContactByDeptID:dep.DEPTID];
    NSArray *departmentArray = [self.depMgr loadDepartments:dep.DEPTID];
    NSMutableArray *mutableArray = [NSMutableArray array];
    [mutableArray addObjectsFromArray:contactArray];
    [mutableArray addObjectsFromArray:departmentArray];
    self.leftView.tableViewList = [mutableArray copy];

    
}

- (void)handleUseGetOrgation
{
    self.curContact = [self.conMgr loadCurContact];
    NSArray *deps = [self.depMgr loadDepartments:@"0"];
    CDepartmentModel *dep = deps.lastObject;
    NSArray *contactArray = [self.conMgr loadContactByDeptID:dep.DEPTID];
    NSArray *departmentArray = [self.depMgr loadDepartments:dep.DEPTID];
    NSMutableArray *mutableArray = [NSMutableArray array];
    [mutableArray addObjectsFromArray:contactArray];
    [mutableArray addObjectsFromArray:departmentArray];
    self.leftView.tableViewList = [mutableArray copy];

}




#pragma organizationvieDeleget
- (void)EFengOrganizationListViewDidSelectedWithName:(NSString *)name indexPath:(NSIndexPath *)indexPath
{
    if ([name isEqualToString:@"群"]) {
        self.type = group;
        self.discussView.hidden = YES;
        self.rightView.hidden = YES;
        self.mineContactView.hidden = YES;
        self.groupView.hidden = NO;
        self.groupView.isAnimation = YES;

    }
    else if ([name isEqualToString:@"讨论组"])
    {
        self.type = discuss;
        self.discussView.hidden = NO;
        self.rightView.hidden = YES;
        self.mineContactView.hidden = YES;
        self.groupView.hidden = YES;
        self.discussView.isAnimation = YES;
    }
    else
    {
        self.type = mineContact;
        self.discussView.hidden = YES;
        self.rightView.hidden = YES;
        self.mineContactView.hidden = NO;
        self.groupView.hidden = YES;
        self.mineContactView.isAnimation = YES;
    }
    [self listBtnClick];
    [self.leftView reloadData];
}
- (void)EFengOrganizationListViewDidSelectedWithModel:(id)Model indexPath:(NSIndexPath *)indexPath
{
    self.isNeedrefresh = YES;
    if ([Model isKindOfClass:[CDepartmentModel class]]) {
        CDepartmentModel *depModel = (CDepartmentModel*)Model;
        [self.fatherDepArray removeAllObjects];
        self.type = organization;
        self.discussView.hidden = YES;
        self.rightView.hidden = NO;
        self.mineContactView.hidden = YES;
        self.groupView.hidden = YES;
            self.curDepModel = Model;
            self.depList = [self.depMgr loadDepartments:depModel.DEPTID];
            self.contactList = [self.conMgr loadContactByDeptID:depModel.DEPTID];
            [self.contactList enumerateObjectsUsingBlock:^(CContactModel  *obj, NSUInteger idx, BOOL *stop) {
                CPresenceModel *presence = [self.preMgr getPresenceWithUserCode:obj.UserCode];
                if ([presence.IsAvailable isEqualToString:@"在线"] || [presence.pcAvailable isEqualToString:@"在线"]) {
                    obj.IsAvailable = @"在线";
                } else {
                    obj.IsAvailable = @"离线";
                }
            }];
            
            
            [self setupDepScrollView];
            [self.leftView reloadData];
            [self.collectionView reloadData];

    }
    if ([Model isKindOfClass:[CContactModel class]]) {
        CContactModel *contact = (CContactModel*)Model;
        if ([contact.UserID isEqualToString:self.curContact.UserID]) {
            MyInformationVC *mine = [[MyInformationVC alloc] init];
        UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
            nav.navigationBarHidden = NO;
            self.navigationController.navigationBarHidden = YES;
            [nav pushViewController:mine animated:YES];
        }
        else
        {
        CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
        chat.group = nil;
        chat.member = contact;
        UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        nav.navigationBarHidden = NO;
        self.navigationController.navigationBarHidden = YES;
        [nav pushViewController:chat animated:YES];
        }
    }
    

}

#pragma mark 搜索相关
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.searchController.searchSectionListArray removeAllObjects];
    [self.searchController.searchAllFirstLetter removeAllObjects];
    NSArray *contactArray = [[[CContactMgr alloc] init] searchContactWithSeachStr:searchText];
    NSArray *groupArray = [[[CGroupMgr alloc] init] searchGroupWithSeachStr:searchText withGroupType:2];
    NSMutableArray *searchArray = [NSMutableArray array];
    [searchArray addObjectsFromArray:contactArray];
    [searchArray addObjectsFromArray:groupArray];
    self.searchController.searchAllFirstLetter = [NSArray IndexArray:searchArray];
    self.searchController.searchSectionListArray = [NSArray LetterSortArray:searchArray];
}


- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar                     // called when text starts editing
{
    searchBar.showsCancelButton = YES;
    for(id cc in [_searchController.searchBar subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
    }
    
}


#pragma mark EFengOrganizationBaseViewDelegate

- (void)eFengOrganizationBaseViewDidSelectedWithContact:(CContactModel *)contact group:(CGroupModel *)group
{
    UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    
    if (contact) {
        
        nav.navigationBarHidden = NO;
        self.navigationController.navigationBarHidden = YES;

        if ([contact.UserID isEqualToString:self.curContact.UserID]) {
            MyInformationVC *mine = [[MyInformationVC alloc] init];
            [nav pushViewController:mine animated:YES];
        } else {
            CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
            chat.group = nil;
            chat.member = contact;
            [nav pushViewController:chat animated:YES];
        }
        return;
    }
    if (group) {
        CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
        chat.group = group;
        chat.member = nil;
        nav.navigationBarHidden = NO;
        self.navigationController.navigationBarHidden = YES;

        [nav pushViewController:chat animated:YES];
    }
}

- (void)eFengOrganizationBaseViewDidCommitEdittingWithContact:(CContactModel *)contact group:(CGroupModel *)group
{
    //删除外部联系人后同时删除跟他的聊天记录
    if ([contact.yuLiuZiduan3 isEqualToString:@"isWaibu"]) {
        [self.conMgr delContactWithContactId:contact.UserID];
        [self addWaiBuContact];
        //彻底删除聊天记录
//        [[[CMessageMgr alloc]init] delMessageWithMineUserId:self.curContact.UserID FriendUserId:contact.UserID];
        //删除外部联系人 但是不删除聊天记录 只是让相关聊天记录不显示 但是还能查到
        [[[CMessageMgr alloc]init] updateMessageWithIsShowInMessageList:NO FriendId:contact.UserID MineId:self.curContact.UserID];
        [[[CMessageDraftMgr alloc]init] delMessageDraftWithFriend:contact.UserID mineId:self.curContact.UserID];

        [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEMESSAGERECORD object:nil];
         }
    else
    {
    CRecentlyContactMgr *reMgr = [[CRecentlyContactMgr alloc] init];
    [reMgr delRecentlyContact:contact.UserID];
    [[CXmppRequestMgr shareInstance] delOftenContactWithUserId:contact.UserID];
    [self addOftenContact];
    }
}

- (void)eFengOrganizationBaseViewDidCreateDisscussion
{
    [self createNewDiscuss];
}
- (void)showMoreView
{
    self.moreView.chatListViewArray = @[@"创建讨论组",@"按部门显示",@"按视图显示"];
    self.isShowMoreView = !self.isShowMoreView;

    if (self.isShowMoreView) {
        [self.moreView showChatListView];
    }
    else
    {
        [self.moreView hieChatListView];
    }

}
-(void)eFengChatListDidSelectWithIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {
            [self createNewDiscuss];
        }
            break;
        case 1:
        {
            CUserSettingModel *model = [[[CUserSettingMgr alloc]init] getUserSetting];
            model.yuLiuZiduan3 = @"按部门显示";
            [[[CUserSettingMgr alloc]init] updateUserSetting:model];
            [self.moreView hieChatListView];
            self.isShowMoreView = NO;
        }
            break;
        case 2:
        {
            CUserSettingModel *model = [[[CUserSettingMgr alloc]init] getUserSetting];
            model.yuLiuZiduan3 = @"按视图显示";
            [[[CUserSettingMgr alloc]init] updateUserSetting:model];
            [self.moreView hieChatListView];
            self.isShowMoreView = NO;
        }
            break;
        default:
            break;
    }

}
-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isNeedrefresh) {
        cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1);
        [UIView animateWithDuration:0.3 animations:^{
            cell.layer.transform = CATransform3DMakeScale(1, 1, 1);
        } completion:^(BOOL finished){
            if (finished) {
                self.isNeedrefresh = NO;
            }
        }];
    }

}
@end
